<template>
  <el-dialog
    v-model="visible"
    width="1400px"
    :title="title"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    destroy-on-close
    @close="dialogClosed"
  >
    <div style="height: 700px">
      <el-steps :active="activeIndex" align-center class="mb-2">
        <el-step title="接口信息" @click="activeIndex = 0" />
        <el-step title="入参设置" @click="activeIndex = 1" />
        <el-step title="出参设置" @click="activeIndex = 2" />
      </el-steps>
      <div style="height: 600px">
        <el-form
          class="h-full"
          ref="formRef"
          :model="form"
          :rules="rules"
          :inline="false"
          label-width="120px"
        >
          <div class="flex flex-row h-full" v-if="activeIndex === 0">
            <el-scrollbar class="w-1/2 pr-4 overflow-auto">
              <el-form-item label="数据库" prop="dataSourceId">
                <el-select v-model="form.dataSourceId" placeholder="请选择数据库" clearable>
                  <el-option
                    v-for="(item, index) in dataListSource"
                    :key="index"
                    :label="`${item.name}（${item.dataSourceType}）`"
                    :value="item.id?.toString()"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="接口名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入接口名称" clearable />
              </el-form-item>
              <el-form-item label="请求方法" prop="httpMethod">
                <el-radio-group v-model="form.httpMethod">
                  <el-radio label="get" value="get" />
                  <el-radio label="post" value="post" />
                </el-radio-group>
              </el-form-item>
              <el-form-item label="请求路径" prop="path">
                <el-input v-model.trim="form.path" placeholder="请输入请求路径" clearable />
              </el-form-item>
              <el-form-item label="请求体参数" prop="paramInBody">
                <el-radio-group v-model="form.paramInBody" @change="paramInBodyChange">
                  <el-radio :value="true" label="是" />
                  <el-radio :value="false" label="否" />
                </el-radio-group>
              </el-form-item>
              <el-form-item v-if="form.paramInBody" label="是否加密传输" prop="encrypt">
                <el-radio-group v-model="form.encrypt" @change="encryptChange">
                  <el-radio :value="true" label="是" />
                  <el-radio :value="false" label="否" />
                </el-radio-group>
              </el-form-item>
              <el-form-item
                v-if="form.paramInBody && form.encrypt"
                label="加密算法"
                prop="encryptAlgorithm"
              >
                <el-radio-group v-model="form.encryptAlgorithm">
                  <el-radio
                    v-for="(item, key) in supportedCryptInfosObj"
                    :key="key"
                    :value="item"
                    :label="item"
                  />
                </el-radio-group>
              </el-form-item>
              <el-form-item
                v-if="form.paramInBody && form.encrypt"
                label="加密KEY"
                prop="encryptKey"
              >
                <el-input
                  v-model="form.encryptKey"
                  type="password"
                  show-password
                  placeholder="请输入加密KEY"
                >
                  <template #suffix>
                    <el-icon class="cursor-pointer" @click="handleCopyClick(form.encryptKey)">
                      <CopyDocument />
                    </el-icon>
                  </template>
                  <template #append>
                    <el-button type="primary" @click="handleGetBodyEncryptKey">自动获取</el-button>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="字段名转换" prop="fieldNameConvertor">
                <el-radio-group v-model="form.fieldNameConvertor">
                  <el-radio
                    v-for="item in field_name_convertor_options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-radio-group>
              </el-form-item>
              <el-form-item label="使用缓存" prop="useCache">
                <el-radio-group v-model="form.useCache">
                  <el-radio :value="true" label="是" />
                  <el-radio :value="false" label="否" />
                </el-radio-group>
              </el-form-item>
              <el-form-item v-if="form.useCache" label="缓存时间(秒)" prop="cacheTime">
                <el-input-number v-model="form.cacheTime" :min="0" :max="36000" />
              </el-form-item>
              <el-form-item label="返回数据量" prop="returnSize">
                <el-radio-group v-model="form.returnSize" @change="handleReturnSizeChange">
                  <el-radio label="单条" value="one" />
                  <el-radio label="多条" value="more" />
                </el-radio-group>
              </el-form-item>
              <el-form-item
                v-if="form.returnSize === 'more'"
                label="查询所有数据"
                prop="allowQueryAllData"
              >
                <el-radio-group v-model="form.allowQueryAllData">
                  <el-radio :value="true" label="是" />
                  <el-radio :value="false" label="否" />
                </el-radio-group>
              </el-form-item>
              <el-form-item
                v-if="form.allowQueryAllData === false"
                label="默认页码"
                prop="defaultPageNum"
              >
                <el-input-number
                  v-model="form.defaultPageSize"
                  :min="1"
                  placeholder="请输入默认页码"
                />
              </el-form-item>
              <el-form-item
                v-if="form.allowQueryAllData === false"
                label="默认页大小"
                prop="defaultPageSize"
              >
                <el-input-number
                  v-model="form.defaultPageNum"
                  :min="1"
                  :max="form.maxPageNum"
                  placeholder="请输入默认页大小"
                />
              </el-form-item>
              <el-form-item
                v-if="form.allowQueryAllData === false"
                label="最大页大小"
                prop="maxPageNum"
              >
                <el-input-number
                  v-model="form.maxPageNum"
                  :min="1"
                  :max="100"
                  @change="maxPageNumChange"
                  placeholder="请输入最大页大小"
                />
              </el-form-item>
              <el-form-item label="标签" prop="tags">
                <el-input v-model="form.tags" placeholder="请输入标签" clearable />
              </el-form-item>
              <el-form-item label="权限属性" prop="open">
                <el-radio-group v-model="form.open" @change="openChange">
                  <el-radio :value="true" label="公开" />
                  <el-radio :value="false" label="私有" />
                </el-radio-group>
              </el-form-item>
              <div v-if="form.open === false">
                <el-form-item label="权限标志" prop="permission">
                  <el-input v-model="form.permission" placeholder="请输入权限标志" clearable />
                </el-form-item>

                <el-form-item label="数据权限方式" prop="dataScopeType">
                  <el-radio-group v-model="form.dataScopeType">
                    <el-radio
                      v-for="(dict, index) in data_scope_type_const_dict"
                      :key="index"
                      :value="dict.value"
                      :label="dict.label"
                      @change="dataScopeTypeChange"
                    />
                  </el-radio-group>
                </el-form-item>

                <el-form-item
                  v-if="form.dataScopeType === 'byDept' || form.dataScopeType === 'byXzqh'"
                  label="用户id字段名"
                  prop="userIdFieldName"
                >
                  <el-input v-model="form.userIdFieldName" placeholder="请输入用户id字段名" />
                </el-form-item>

                <el-form-item
                  v-if="form.dataScopeType === 'byDept'"
                  label="部门id字段名"
                  prop="deptIdFieldName"
                >
                  <el-input v-model="form.deptIdFieldName" placeholder="请输入部门id字段名" />
                </el-form-item>

                <el-form-item
                  v-if="form.dataScopeType === 'byXzqh'"
                  label="区字段名"
                  prop="quFieldName"
                >
                  <el-input v-model="form.quFieldName" placeholder="请输入区字段名" />
                </el-form-item>

                <el-form-item
                  v-if="form.dataScopeType === 'byXzqh'"
                  label="街道字段名"
                  prop="jdFieldName"
                >
                  <el-input v-model="form.jdFieldName" placeholder="请输入街道字段名" />
                </el-form-item>

                <el-form-item
                  v-if="form.dataScopeType === 'byXzqh'"
                  label="社区字段名"
                  prop="sqFieldName"
                >
                  <el-input v-model="form.sqFieldName" placeholder="请输入社区字段名" />
                </el-form-item>

                <el-form-item
                  v-if="form.dataScopeType === 'byXzqh'"
                  label="网格字段名"
                  prop="wgFieldName"
                >
                  <el-input v-model="form.wgFieldName" placeholder="请输入网格字段名" />
                </el-form-item>

                <el-form-item
                  v-if="form.dataScopeType === 'byXzqh'"
                  label="小区字段名"
                  prop="xqFieldName"
                >
                  <el-input v-model="form.xqFieldName" placeholder="请输入小区字段名" />
                </el-form-item>
              </div>
            </el-scrollbar>
            <div class="w-1/2">
              <el-form-item
                class="h-full sql-form-item"
                label="查询SQL"
                prop="sql"
                label-width="80px"
              >
                <div class="w-full h-full">
                  <div class="flex flex-row justify-end">
                    <el-tooltip class="item" effect="dark" placement="top">
                      <el-icon class="cursor-pointer" style="font-size: 20px">
                        <question-filled />
                      </el-icon>
                      <template #content>
                        <div style="width: 250px">
                          <div>1、sql不建议${}方式取参。</div>
                          <div>
                            2、sql内容为mybatis.xml中select标签中的内容，注意xml的关键字符需要转义。
                          </div>
                          <div>参数字段名：</div>
                          <div>以下所述字段名可以在sql中直接使用#{}引用。</div>
                          <div>1、入参body是数组，则从list或collection中取入参，如#{list}。</div>
                          <div>2、入参body是对象，则直接使用字段名取入参。</div>
                          <div>3、分页参数字段名__page。</div>
                          <div>4、用户id、部门id、用户账号的字段名为userId、deptId、username。</div>
                          <div>
                            5、用户所属行政区划-省、市、区、街道、社区、网格、小区字段名为xzqhProvince、xzqhCity、xzqhDistrict、xzqhStreet、xzqhCommunity、xzqhWg、xzqhXq。
                          </div>
                        </div>
                      </template>
                    </el-tooltip>
                  </div>
                  <div class="font-bold mt-2">
                    <div>{{ sqlPresetText[0] }}</div>
                    <div class="ml-2">
                      {{ sqlPresetText[1] }} {{ form.path }} {{ sqlPresetText[2] }}
                    </div>
                    <CodeEditor v-model:value="form.sql" height="450px" />
                    <div class="ml-2">{{ sqlPresetText[3] }}</div>
                    <div>{{ sqlPresetText[4] }}</div>
                  </div>
                </div>
              </el-form-item>
            </div>
          </div>
          <div v-if="activeIndex === 1">
            <el-button type="primary" icon="Plus" style="margin-bottom: 8px" @click="addApiParams">
              新增入参
            </el-button>
            <el-table :data="form.apiParams" border height="560">
              <el-table-column label="参数名" prop="name" align="center">
                <template #default="{ row }">
                  <el-input
                    v-if="row.isEdit"
                    v-model="row.name"
                    placeholder="请输入参数名"
                    clearable
                  />
                  <span v-else>{{ row.name }}</span>
                </template>
              </el-table-column>
              <el-table-column label="参数示例" prop="example" align="center">
                <template #default="{ row }">
                  <el-input
                    v-if="row.isEdit"
                    v-model="row.example"
                    placeholder="请输入参数示例"
                    clearable
                  />
                  <span v-else>{{ row.example }}</span>
                </template>
              </el-table-column>
              <el-table-column label="参数描述" prop="remark" align="center">
                <template #default="{ row }">
                  <el-input
                    v-if="row.isEdit"
                    v-model="row.remark"
                    placeholder="请输入参数描述"
                    clearable
                  />
                  <span v-else>{{ row.remark }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="140">
                <template #default="{ row, $index }">
                  <template v-if="row.isEdit">
                    <el-button type="success" link @click="saveApiParams(row)"> 保存 </el-button>
                    <el-button type="warning" link @click="undoApiParams(row)"> 取消 </el-button>
                  </template>
                  <template v-else>
                    <el-button type="primary" link @click="editApiParams(row)"> 修改 </el-button>
                    <el-button type="danger" link @click="delApiParams($index)"> 删除 </el-button>
                  </template>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div v-if="activeIndex === 2">
            <el-button type="primary" icon="Plus" style="margin-bottom: 8px" @click="addApiReturns">
              新增出参
            </el-button>
            <el-table :data="form.apiReturns" border height="560">
              <el-table-column label="参数名" prop="name" align="center">
                <template #default="{ row }">
                  <el-input
                    v-if="row.isEdit"
                    v-model="row.name"
                    placeholder="请输入参数名"
                    clearable
                  />
                  <span v-else>{{ row.name }}</span>
                </template>
              </el-table-column>
              <el-table-column label="参数示例" prop="example" align="center">
                <template #default="{ row }">
                  <el-input
                    v-if="row.isEdit"
                    v-model="row.example"
                    placeholder="请输入参数示例"
                    clearable
                  />
                  <span v-else>{{ row.example }}</span>
                </template>
              </el-table-column>
              <el-table-column label="参数描述" prop="remark" align="center">
                <template #default="{ row }">
                  <el-input
                    v-if="row.isEdit"
                    v-model="row.remark"
                    placeholder="请输入参数描述"
                    clearable
                  />
                  <span v-else>{{ row.remark }}</span>
                </template>
              </el-table-column>
              <el-table-column label="是否需要脱敏" prop="needDesensitize" align="center">
                <template #default="{ row }">
                  <el-radio-group v-if="row.isEdit" v-model="row.needDesensitize">
                    <el-radio :value="true" label="是" />
                    <el-radio :value="false" label="否" />
                  </el-radio-group>
                  <span v-else>{{ formatBoolean(row.needDesensitize) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="脱敏方式" prop="desensitization" align="center">
                <template #default="{ row }">
                  <el-select
                    v-if="row.isEdit"
                    v-model="row.desensitization"
                    placeholder="请选择脱敏方式"
                    clearable
                  >
                    <el-option
                      v-for="(item, key) in sensitive_type"
                      :key="key"
                      :value="item.value"
                      :label="item.label"
                    />
                  </el-select>
                  <span v-else>{{ formatDesensitization(row.desensitization) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="140">
                <template #default="{ row, $index }">
                  <template v-if="row.isEdit">
                    <el-button type="success" link @click="saveApiReturns(row)"> 保存 </el-button>
                    <el-button type="warning" link @click="undoApiReturns(row)"> 取消 </el-button>
                  </template>
                  <template v-else>
                    <el-button type="primary" link @click="editApiReturns(row)"> 修改 </el-button>
                    <el-button type="danger" link @click="delApiReturns($index)"> 删除 </el-button>
                  </template>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form>
      </div>
      <div class="flex flex-row items-center justify-end mt-2">
        <el-button v-show="activeIndex !== 0" type="primary" @click="handlePrevStep">
          上一步
        </el-button>
        <el-button v-show="activeIndex !== 2" type="primary" @click="handleNextStep">
          下一步
        </el-button>
        <el-button type="primary" @click="submitForm"> 确认</el-button>
        <el-button @click="visible = false">取消</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
  import { ref, computed, watch, defineProps, defineEmits, unref } from 'vue';
  import { addApiDetail, updateApiDetail } from '@/api/web/db/api/api-list';
  import { getSupportedCryptInfos, schemaValidate } from '@/api/web/db/api/api-detail';
  import { listSource } from '@/api/web/bu/form';
  import { CodeEditor } from '@/components/CodeEditor';
  import { randomHex } from '@/utils';
  import { CopyDocument } from '@element-plus/icons-vue';
  import { useCopyToClipboard } from '@/hooks/web/useCopyToClipboard';
  import { useDict } from '@/utils/dict';
  import { selectDictLabel } from '@/utils/base';
  import modal from '@/plugins/modal';

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
    },
    currentItem: {
      type: Object,
      default: () => ({}),
    },
  });

  const emits = defineEmits(['update:modelValue', 'success']);

  const { clipboardRef, copiedRef } = useCopyToClipboard();

  const { field_name_convertor_options, data_scope_type_const_dict, sensitive_type } = useDict(
    'field_name_convertor_options',
    'data_scope_type_const_dict',
    'sensitive_type',
  );

  const visible = computed({
    set(val) {
      emits('update:modelValue', val);
    },
    get() {
      return props.modelValue;
    },
  });

  const sqlPresetText = ref([
    '<mapper namespace="dataApi">',
    '<select id="',
    '" parameterType="map" resultMap="map">',
    '</select>',
    '</mapper>',
  ]);

  const dataListSource = ref([]);
  const supportedCryptInfosObj = ref([]);

  const activeIndex = ref(0);
  const title = ref('');
  const formRef = ref(null);
  const form = ref({});
  const rules = ref({
    dataSourceId: [{ required: true, message: '数据库名称不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '请输入接口名称', trigger: 'blur' }],
    paramInBody: [{ required: true, message: '请输入请求体参数', trigger: 'blur' }],
    fieldNameConvertor: [{ required: true, message: '请输入字段名转换', trigger: 'blur' }],
    useCache: [{ required: true, message: '请选择是否使用缓存', trigger: 'blur' }],
    returnSize: [{ required: true, message: '请选择返回数据量', trigger: 'blur' }],
    encrypt: [{ required: true, message: '请选择是否加密传输', trigger: 'blur' }],
    encryptAlgorithm: [{ required: true, message: '请选择加密算法', trigger: 'blur' }],
    encryptKey: [{ required: true, message: '请输入加密KEY', trigger: 'blur' }],
    open: [{ required: true, message: '请选择权限属性', trigger: 'blur' }],
    permission: [{ required: true, message: '请输入权限标志', trigger: 'blur' }],
    path: [
      { required: true, message: '请求路径不能为空', trigger: 'blur' },
      { validator: checkPath, trigger: 'change' },
    ],
    httpMethod: [{ required: true, message: '请求方法不能为空', trigger: 'blur' }],
    dataScopeType: [{ required: true, message: '请选择数据权限方式', trigger: 'blur' }],
    sql: [{ required: true, message: '查询SQL不能为空', trigger: 'blur' }],
  });

  watch(visible, (v) => {
    if (v) {
      if (props.currentItem) {
        reset();
        form.value = props.currentItem;
        title.value = `${props.currentItem.id ? '修改' : '复制'}在线接口`;
        activeIndex.value = 0;
      } else {
        reset();
        initForm();
        title.value = '新增在线接口';
        activeIndex.value = 0;
      }
    }
  });

  function reset() {
    form.value = {
      id: null,
      allowQueryAllData: null, // 允许查询所有数据
      apiParams: [],
      apiReturns: [],
      cacheTime: null, // 缓存时间
      dataScopeType: null, // 数据权限方式
      dataSourceId: null, // 数据源ID
      defaultPageNum: null, // 默认页大小
      defaultPageSize: null, // 默认页码
      maxPageNum: null, // 最大页大小
      encrypt: null, //
      encryptAlgorithm: null, //
      encryptKey: null, //
      fieldNameConvertor: null, // 字段名转换器
      httpMethod: null, // 请求方法
      name: null, // 接口名称
      open: null, // 是否公开
      paramInBody: null, // 是否请求体参数
      path: null, // 请求路径
      permission: null, // 权限标志
      returnSize: null, // 返回数量
      roleTag: null, // 权限标志
      sql: null, // 查询SQL
      tags: null, // 标签
      useCache: null, // 是否使用缓存
      userIdFieldName: null, // 用户ID字段名
      deptIdFieldName: null, // 部门ID字段名
      quFieldName: null, // 区字段名
      jdFieldName: null, // 街道字段名
      sqFieldName: null, // 社区字段名
      wgFieldName: null, // 网格字段名
      xqFieldName: null, // 小区字段名
      createTime: null,
      createBy: null,
      updateTime: null,
      updateBy: null,
    };
    formRef.value?.resetFields();
  }

  function initForm() {
    form.value.paramInBody = true;
    form.value.fieldNameConvertor = 'cameCase';
    form.value.useCache = false;
    form.value.httpMethod = 'post';
    form.value.returnSize = 'more';
    form.value.allowQueryAllData = false;
    form.value.defaultPageSize = 1;
    form.value.defaultPageNum = 10;
    form.value.maxPageNum = 100;
    form.value.encrypt = false;
    form.value.open = true;
  }

  function submitForm() {
    formRef.value.validate((valid) => {
      if (valid) {
        if (form.value.id) {
          updateApiDetail(form.value).then(() => {
            modal.msgSuccess('修改成功');
            visible.value = false;
            emits('success');
          });
        } else {
          addApiDetail(form.value).then(() => {
            modal.msgSuccess('新增成功');
            visible.value = false;
            emits('success');
          });
        }
      }
    });
  }

  function handlePrevStep() {
    activeIndex.value -= 1;
  }

  function handleNextStep() {
    if (activeIndex.value === 0) {
      formRef.value.validate((valid) => {
        if (valid) {
          schemaValidate({ xml: encodeURIComponent(form.value.sql) }).then((result) => {
            if (result.data) {
              activeIndex.value += 1;
            } else {
              modal.msgError('SQL验证不通过');
            }
          });
        }
      });
    } else {
      activeIndex.value += 1;
    }
  }

  function checkPath(rule, value, callback) {
    let z = /^[a-zA-Z][a-zA-Z0-9.\-_/]{0,254}/;
    if (!z.test(value)) {
      return callback(
        new Error(
          '请求路径需以大小写字母开头，以大小写字母、数字、点、横杠、下划线、右斜杠组成, 1-255个字符',
        ),
      );
    }
    if (!value) {
      return callback(new Error('请求路径不能为空'));
    }
    if (value?.startsWith('/')) {
      return callback(new Error('请求路径不能以/开头'));
    }
    callback();
  }

  function paramInBodyChange(val) {
    if (!val) {
      form.value.paramInBody = false;
      form.value.encrypt = false;
    }
  }

  // 加密传输后设置的初始值
  function encryptChange(val) {
    // 加密传输为true，需要encryptKey和encryptAlgorithm
    if (val && !form.value.encryptKey) {
      // 判断是否有容器有是否有数据，没有则说明没修改过需要生成;没有就将容器的值赋值给他
      form.value.encryptKey = randomHex(32);
    }
    if (val && !form.value.encryptAlgorithm) {
      // 判断是否有容器有是否有数据，没有则说明没修改过需要生成;没有就将容器的值赋值给他
      form.value.encryptAlgorithm = 'SM4';
    }
  }

  // 当"最大页大小"的值改变时，确保"默认页大小"的值不超过新的"最大页大小"的值
  function maxPageNumChange() {
    if (form.value.defaultPageNum > form.value.maxPageNum) {
      form.value.defaultPageNum = form.value.maxPageNum;
    }
  }

  function handleCopyClick(v) {
    clipboardRef.value = v;
    if (unref(copiedRef)) {
      modal.msgSuccess('复制成功');
    }
  }

  function handleGetBodyEncryptKey() {
    form.value.encryptKey = randomHex(32);
  }

  function handleReturnSizeChange() {
    form.value.allowQueryAllData = null;
  }

  // 选中私有属性后数据权限为不限制
  function openChange(val) {
    if (!val) {
      form.value.dataScopeType = 'noLimit';
    } else {
      form.value.dataScopeType = null;
    }
  }

  // 选中数据权限方式后
  function dataScopeTypeChange(val) {
    if (val === 'byDept') {
      form.value.userIdFieldName = 'user_id';
      form.value.deptIdFieldName = 'dept_id';
    } else if (val === 'byXzqh') {
      form.value.userIdFieldName = 'user_id';
      form.value.quFieldName = 'district';
      form.value.jdFieldName = 'street';
      form.value.sqFieldName = 'community';
      form.value.wgFieldName = 'wg';
      form.value.xqFieldName = 'xq';
    } else {
      form.value.userIdFieldName = null;
      form.value.deptIdFieldName = null;
      form.value.quFieldName = null;
      form.value.jdFieldName = null;
      form.value.sqFieldName = null;
      form.value.wgFieldName = null;
      form.value.xqFieldName = null;
    }
  }

  function addApiReturns() {
    const one = {
      id: null,
      apiId: null,
      name: null,
      example: null,
      remark: null,
      needDesensitize: false,
      desensitization: null,
      isEdit: true,
    };
    one.backup = { ...one, isEdit: false };
    form.value.apiReturns.push(one);
  }

  function delApiReturns(index) {
    form.value.apiReturns.splice(index, 1);
  }

  function editApiReturns(row) {
    row.backup = { ...row };
    row.isEdit = true;
  }

  function saveApiReturns(row) {
    delete row.backup;
    row.isEdit = false;
  }

  function undoApiReturns(row) {
    Object.assign(row, row.backup);
    delete row.backup;
    row.isEdit = false;
  }

  function addApiParams() {
    const one = {
      id: null,
      apiId: null,
      encryptAlgorithm: null,
      encryptKey: null,
      example: null,
      name: null,
      needEncrypt: null,
      paramType: null,
      remark: null,
      isEdit: true,
    };
    one.backup = { ...one, isEdit: false };
    form.value.apiParams.push(one);
  }

  function delApiParams(index) {
    form.value.apiParams.splice(index, 1);
  }

  function editApiParams(row) {
    row.backup = { ...row };
    row.isEdit = true;
  }

  function saveApiParams(row) {
    delete row.backup;
    row.isEdit = false;
  }

  function undoApiParams(row) {
    Object.assign(row, row.backup);
    delete row.backup;
    row.isEdit = false;
  }

  function formatBoolean(value) {
    if (value === null || value === undefined) {
      return '';
    }
    return value ? '是' : '否';
  }

  function formatDesensitization(value) {
    return selectDictLabel(sensitive_type.value, value);
  }

  function dialogClosed() {
    activeIndex.value = 0;
    title.value = '';
    reset();
  }

  function getListSource() {
    listSource().then((res) => {
      dataListSource.value = res.data;
    });
  }

  function getCryptInfosList() {
    getSupportedCryptInfos().then((res) => {
      supportedCryptInfosObj.value = res.data;
    });
  }

  getListSource();
  getCryptInfosList();
</script>

<style scoped lang="scss">
  .sql-form-item {
    :deep(.el-form-item__label) {
      position: absolute;
    }
  }
</style>
